package com.meraklisina.latexeditor;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextPane;

import com.meraklisina.latexeditor.mdi.TextEditor.TextEditors;

public class ProjectHelpers {

	ArrayList<String> SectionName = new ArrayList<String>();
	ArrayList<String> SectionLine = new ArrayList<String>();
	
	public int FindLineNumberAtCaretPosition(int caretPosition, JTabbedPane tab_editor)
	{
		JTextPane selectedEditor = getTextEditor(tab_editor);
    	StringBuffer sb = new StringBuffer(selectedEditor.getText());
    	
        int j=1;
        for(int i=0; i<sb.length(); i++) {
           if(sb.charAt(i)=='\n')j++;
              if(i==caretPosition){
                return j;
              }
        }
        
        return 0;
	}
	
	public JTextPane getTextEditor(JTabbedPane tab_editor)
    {
        return new TextEditors().GetJTextPaneAt(tab_editor, tab_editor.getSelectedIndex());
    }
	
	public void FillSectionArray(JTabbedPane tab_editor, JComboBox comboBox)
	{
		JTextPane selectedEditor = getTextEditor(tab_editor);
    	StringBuffer sb = new StringBuffer(selectedEditor.getText());
    	
    	SectionName.clear();
    	SectionLine.clear();
    	
    	FindAndAddSection("section", SectionName, SectionLine, sb, tab_editor);
    	FindAndAddSection("subsection", SectionName, SectionLine, sb, tab_editor);
    	FindAndAddSection("subsubsection", SectionName, SectionLine, sb, tab_editor);
    	FindAndAddSection("paragraph", SectionName, SectionLine, sb, tab_editor);
    	FindAndAddSection("subparagraph", SectionName, SectionLine, sb, tab_editor);
    	
    	SortSectionArray(SectionName, SectionLine);
    	
    	FillSectionsComboBox(SectionName, SectionLine, comboBox);
	}
	
	public void FindAndAddSection(String SectionName, ArrayList<String> nameList, ArrayList<String> lineList, StringBuffer sb, JTabbedPane tab_editor)
	{
		int endOfSection = 0;
    	String nameOfSection = "";
	
		int startPoint = 0;
		int position = 0;
		
		while (true)
		{
			String toSearch = sb.substring(startPoint);
			if (toSearch.contains("\\" + SectionName))
			{
				position = toSearch.indexOf("\\" + SectionName);
				endOfSection = toSearch.substring(position).indexOf("}");
				nameOfSection = toSearch.substring(position,endOfSection+position+1);
				nameList.add(nameOfSection);
				lineList.add(Integer.toString(FindLineNumberAtCaretPosition(startPoint+position, tab_editor)));
				startPoint = startPoint + endOfSection + position + 1;
			}
			else
			{
				break;
			}
		}
	}
	
	public void SortSectionArray(ArrayList<String> nameList, ArrayList<String> lineList)
	{
		for (int i=0; i< lineList.size();i++)
		{
			for (int j=0; j< lineList.size() - i; j++)
			{
				if (Integer.parseInt(lineList.get(i)) > Integer.parseInt(lineList.get(j+i)))
				{
					String tempName = nameList.get(j+i); 
					nameList.set(j+i, nameList.get(i));
					nameList.set(i, tempName);
					
					String tempLine = lineList.get(j+i);
					lineList.set(j+i, lineList.get(i));
					lineList.set(i, tempLine);
				}
			}
				
		}
	}
	
	public void FillSectionsComboBox(ArrayList<String> nameList, ArrayList<String> lineList, JComboBox comboBox)
	{
		comboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"Sections"}));
		
		int section = 0;
		int subsection = 0;
		int subsubsection = 0;
		int paragraph = 0;
		int subparagraph = 0;
		
		ArrayList<String> itemsToFill = new ArrayList<String>();
		
		for (int i=0; i<nameList.size();i++)
		{
			String name = nameList.get(i);
			int bracketOpened = name.indexOf("{")+1;
			int bracketClosed = name.lastIndexOf("}");
						
			if (name.substring(1, 8).equalsIgnoreCase("section"))
			{
				section++;
				subsection = 0;
				subsubsection = 0;
				paragraph = 0;
				subparagraph = 0;
				String write = Integer.toString(section) + "." + name.substring(bracketOpened,bracketClosed);
				itemsToFill.add(write);
			}
			else if (name.substring(1, 11).equalsIgnoreCase("subsection"))
			{
				subsection++;
				subsubsection = 0;
				paragraph = 0;
				subparagraph = 0;
				String write = "  " + Integer.toString(section) + "." + Integer.toString(subsection) + "." + name.substring(bracketOpened,bracketClosed);
				itemsToFill.add(write);
			}
			else if (name.substring(1,14).equalsIgnoreCase("subsubsection"))
			{
				subsubsection++;
				paragraph = 0;
				subparagraph = 0;
				String write = "    " + Integer.toString(section) + "." + Integer.toString(subsection) + "." + Integer.toString(subsubsection) + "." + name.substring(bracketOpened,bracketClosed);
				itemsToFill.add(write);
			}
			else if (name.substring(1, 10).equalsIgnoreCase("paragraph"))
			{
				paragraph++;
				subparagraph = 0;
				String write = "      " + Integer.toString(section) + "." + Integer.toString(subsection) + "." + Integer.toString(subsubsection) + "." + Integer.toString(paragraph) + "." + name.substring(bracketOpened,bracketClosed);
				itemsToFill.add(write);
			}
			else if (name.substring(1, 13).equalsIgnoreCase("subparagraph"))
			{
				subparagraph++;
				String write = "        " + Integer.toString(section) + "." + Integer.toString(subsection) + "." + Integer.toString(subsubsection) + "." + Integer.toString(paragraph) + "." + Integer.toString(subparagraph) + "." +name.substring(bracketOpened,bracketClosed);
				itemsToFill.add(write);
			}
		}
		
		if (itemsToFill.size() == 0)
			comboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"No Section"}));
		else
		{
			comboBox.setModel(new javax.swing.DefaultComboBoxModel(itemsToFill.toArray()));
			comboBox.showPopup();
		}
	}
	
	public int GetLineNumberOfSection(int ComboBoxSelectedIndex)
	{
		return Integer.parseInt(SectionLine.get(ComboBoxSelectedIndex));
	}
		
	public void GoToSelectedLine(int line, JTabbedPane tab_editor)
    {
    	JTextPane selectedEditor = new TextEditors().GetJTextPaneAt(tab_editor, tab_editor.getSelectedIndex());
    	StringBuffer sb = new StringBuffer(selectedEditor.getText());
    	
        int j=1;
        for(int i=0; i<sb.length(); i++) {
           if(sb.charAt(i)=='\n')j++;
              if(j==line){
                j=i;
                break;
              }
        }
        
        if (line == 1)
        {
        	j = 0;
        }
        else if (line > j)
    	{
    		JOptionPane.showMessageDialog(null, "There is less line than the specified number", "Error", JOptionPane.ERROR_MESSAGE);
    		return;
    	}
        else if (line < 0)
        {
        	JOptionPane.showMessageDialog(null, "You cannot go to this line", "Error", JOptionPane.ERROR_MESSAGE);
    		return;
        }
        
        try{
        	selectedEditor.requestFocus();
        	selectedEditor.setCaretPosition(j+2-line);
        }catch (IllegalArgumentException exc) { System.err.println("goToLine() "+exc); }
    }
	
	public String[] FindExistingLanguageFiles()
	{
		File dir = new File("lang");
		final String ff = ".xml";

		FilenameFilter filter = new FilenameFilter() {
			
			//@Override
			public boolean accept(File dir, String name) {

				if (name.endsWith(ff))
					return true;
				
				return false;
			}
		}; 
		
        String[] children = dir.list(filter);
        
        for (int i=0; i< children.length;i++)
        {
        	children[i] = children[i].substring(0, children[i].length()-4);
        }
        
        return children;
	}
}
